package com.gutai.admin.controller;

import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.gutai.admin.common.entity.dto.SelectListDto;
import com.gutai.admin.common.entity.dto.UserCouponDto;
import com.gutai.admin.common.entity.response.Response;
import com.gutai.admin.common.util.ExceptionUtils;
import com.gutai.admin.common.util.ResponseHelper;
import com.gutai.admin.entity.Cart;
import com.gutai.admin.entity.User;
import com.gutai.admin.service.IUserService;

/**
 * 
 * 描述：
 * 
 * <pre>
 * HISTORY
 * ****************************************************************************
 *  ID    DATE            PERSON            REASON
 *  1     2018年11月7日         YC           Create
 * ****************************************************************************
 * </pre>
 * 
 * @author YC
 * @version 1.0
 */
@RestController
@RequestMapping("/user")
public class UserController {

    private static final Logger logger = LoggerFactory.getLogger(UserController.class);

    @Autowired
    private IUserService userService;

    @CrossOrigin
    @GetMapping("/listAll")
    public Response listAll(String name, Integer startPage, Integer pageSize) {
        try {
            if (StringUtils.isNotBlank(name)) {
                List<User> list = userService.findByName(name);
                return ResponseHelper.buildOk(list);
            } else {
                if (startPage == null || startPage < 1) {
                    startPage = 1;
                }
                if (pageSize == null) {
                    pageSize = 10;
                }
                Page<User> list = userService.getList(startPage, pageSize);
                return ResponseHelper.buildOk(list.getContent(), list.getTotalElements());
            }
        } catch (Exception e) {
            logger.error(" --{}", ExceptionUtils.extractStackTrace(e));
            return ResponseHelper.buildFail(e.getMessage());
        }
    }

    @CrossOrigin
    @GetMapping("/selectList")
    public Response selectList() {
        try {
//            Set<User> datas = (Set<User>) LocalCacheUtil.getElems(User.class.getName());
//            if (CollectionUtil.isEmpty(datas)) {
//                datas = new HashSet<>(userService.getAll());
//                LocalCacheUtil.addOrUpd(User.class.getName(), datas);
//            }
            List<SelectListDto> selectList = userService.getAll().stream()
                    .sorted(Comparator.comparingLong(User::getCreateTime).reversed())
                    .map(data -> new SelectListDto(data.getId(), data.getUsername()))
                    .collect(Collectors.toList());
            return ResponseHelper.buildOk(selectList);
        } catch (Exception e) {
            logger.error(" --{}", ExceptionUtils.extractStackTrace(e));
            return ResponseHelper.buildFail(e.getMessage());
        }
    }

    @CrossOrigin
    @PostMapping("/add")
    public Response add(@RequestBody User entity) {
        try {
            userService.add(entity);
            return ResponseHelper.buildOk();
        } catch (Exception e) {
            logger.error(" --{}", ExceptionUtils.extractStackTrace(e));
            return ResponseHelper.buildFail("操作DB失败:" + e.getMessage());
        }
    }

    @CrossOrigin
    @PostMapping("/update")
    public Response update(@RequestBody User entity) {
        try {
            userService.update(entity);
            return ResponseHelper.buildOk();
        } catch (Exception e) {
            logger.error(" --{}", ExceptionUtils.extractStackTrace(e));
            return ResponseHelper.buildFail("操作DB失败:" + e.getMessage());
        }
    }

    @CrossOrigin
    @GetMapping("/delete")
    public Response delete(Integer id) {
        try {
            userService.delete(id);
            return ResponseHelper.buildOk();
        } catch (Exception e) {
            logger.error(" --{}", ExceptionUtils.extractStackTrace(e));
            return ResponseHelper.buildFail("操作DB失败:" + e.getMessage());
        }
    }

    @CrossOrigin
    @GetMapping("/findById")
    public Response findById(Integer userId, Integer rowId) {
        try {
            // System.err.println("userid:" + userId + ", rowId:" + rowId);
            User data = userService.findById(userId);
            Response res = ResponseHelper.buildOk(data);
            res.setMsg(String.valueOf(rowId));
            return res;
        } catch (Exception e) {
            logger.error(" --{}", ExceptionUtils.extractStackTrace(e));
            return ResponseHelper.buildFail(e.getMessage());
        }
    }

    @CrossOrigin
    @GetMapping("/selectCoupons")
    public Response selectCoupons(Integer userId) {
        try {
            List<UserCouponDto> datas = userService.getByUserId(userId);
            return ResponseHelper.buildOk(datas);
        } catch (Exception e) {
            logger.error(" --{}", ExceptionUtils.extractStackTrace(e));
            return ResponseHelper.buildFail(e.getMessage());
        }
    }

    @CrossOrigin
    @GetMapping("/selectCarts")
    public Response selectCarts(Integer userId) {
        try {
            List<Cart> datas = userService.getCartByUserId(userId);
            Response res = ResponseHelper.buildOk(datas);
            res.setMsg(String.valueOf(userId));
            return res;
        } catch (Exception e) {
            logger.error(" --{}", ExceptionUtils.extractStackTrace(e));
            return ResponseHelper.buildFail(e.getMessage());
        }
    }

}
